//
//  ICFileScanController.m
//  ICome
//
//  Created by ENN on 16/7/21.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICFileScanController.h"
#import <QuickLook/QuickLook.h>
#import "ICAudioView.h"
#import "ICFileTool.h"
#import "ICHeaderFile.h"

@interface ICFileScanController ()<QLPreviewControllerDataSource,QLPreviewControllerDelegate,UIWebViewDelegate,UIDocumentInteractionControllerDelegate>

@property (nonatomic, weak) UIWebView *webView;
@property (nonatomic, strong) QLPreviewController *previewController;
@property (nonatomic, strong) NSURL *fileURL;
@property (nonatomic, strong) UIDocumentInteractionController *documentInCtr;
@property (nonatomic, weak) ICAudioView *audioView;

@end

@implementation ICFileScanController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    
    if (self.isFun) {
        
        [self setDataWithExtType:self.extType fileKey:self.fileKey];
    }else
    {
        self.fileURL = [NSURL fileURLWithPath:self.filePath];
        NSString *type = [self.filePath pathExtension];
        [self setupVew:type];
    }
}


- (void)setupNav
{
    self.title = _orgName;
}


- (void)setDataWithExtType:(NSString *)extType fileKey:(NSString *)fileKey
{
    NSString *path   = [[ICMediaManager sharedManager] deliverFilePath:fileKey type:extType];
    self.filePath = path;
    NSURL *pathURL   = [NSURL fileURLWithPath:path];
    self.fileURL     = pathURL;
    if ([ICFileTool fileExistsAtPath:path]) {
        
        [self setupVew:extType];
        // [MBProgressHUD hideLoadingActivityView:self.view];
    }else
    {
        
        if ([ICTools isFile:extType]) {
            
            [self previewController];
        }
        [MBProgressHUD showMessage:@"请稍候..." toView:self.view];
        __weak typeof(self)weak_self = self;
        [[ICNetworkManager sharedInstance] getFile:fileKey progress:nil success:^(id object) {
            NSData *fileData = [NSData dataWithData:object];
            BOOL result = [fileData writeToFile:path atomically:NO];
            if (!result) NSLog(@"write deliver file error");
            NSURL *pathURL   = [NSURL fileURLWithPath:path];
            self.fileURL     = pathURL;
            // [weak_self fileAlreadExist:path type:extType];
            [self setupVew:extType];
            
            [MBProgressHUD hideLoadingActivityView:weak_self.view];
        } failure:^(NSError *error) {
            NSLog(@"getFile error:%@",error);
            
            [MBProgressHUD hideLoadingActivityView:weak_self.view];
        }];
    }
}

- (void)setupVew:(NSString *)type
{
    if ([type isEqualToString:@"html"] || [type isEqualToString:@"htm"]) {
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.width,APP_Frame_Height - ([ICTools getStatusbarHeight] + [ICTools getNavbarHeight]))];
        webView.delegate = self;
        //        webView.scalesPageToFit = YES;
        [self.view addSubview:webView];
        _webView           = webView;
        webView.scrollView.backgroundColor = [UIColor whiteColor];
        [self webViewLoadData:type];
        
    }else if ([ICTools isFile:type]){
        
        [self.previewController reloadData];
        
    }  else if ([ICTools isImage:type]) {
        UIImageView *imageV = [[UIImageView alloc] init];
        [self.view addSubview:imageV];
        UIImage *image = [UIImage imageWithContentsOfFile:self.filePath];
        if (image) {
            imageV.frame = CGRectMake(0, 0, App_Frame_Width, image.size.height * App_Frame_Width /  image.size.width);
            imageV.center = CGPointMake(self.view.width*0.5, self.view.height*0.5);
            imageV.image   = image;
        }
        
    } else if ([ICTools isVoiceFrequency:type]) {
        ICAudioView *audioView = [[ICAudioView alloc] initWithFrame:CGRectMake(0,0, App_Frame_Width, APP_Frame_Height)];
        audioView.audioPath = self.filePath;
        audioView.audioName = self.orgName;
        [self.view addSubview:audioView];
        _audioView = audioView;
        
    } else {
        [self makeOtherView];
    }
}

- (QLPreviewController *)previewController
{
    if (!_previewController) {
        
        _previewController = [[QLPreviewController alloc] init];
        _previewController.dataSource = self;
        _previewController.delegate   = self;
        _previewController.view.frame = CGRectMake(0,0, App_Frame_Width, APP_Frame_Height - ([ICTools getStatusbarHeight] + [ICTools getNavbarHeight]));
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        NSLog(@"%@",[ICTools getSystemVersion]);
        [self addChildViewController:_previewController];
        [self.view addSubview:_previewController.view];
        [_previewController didMoveToParentViewController:self];
    }
    return _previewController;
}

- (void)makeOtherView
{
    UIImageView *imageV = [[UIImageView alloc] init];
    imageV.frame        = CGRectMake(App_Frame_Width*0.5-40, 45, 80, 80);
    imageV.image        = [UIImage imageNamedFromiComeSDKBundle:@"icon_type_file"];
    [self.view addSubview:imageV];
    UILabel *nameL      = [[UILabel alloc] initWithFrame:CGRectMake(App_Frame_Width*0.5-150, imageV.bottom+32, 300, 40)];
    nameL.text          = [self.filePath lastPathComponent];
    nameL.font          = [UIFont systemFontOfSize:15];
    nameL.textColor     = ICRGB(0x505f62);
    nameL.numberOfLines = 0;
    nameL.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:nameL];
    [nameL sizeToFit];
    nameL.centerX = App_Frame_Width*0.5;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(App_Frame_Width*0.5-100, nameL.bottom+85, 200, 40)];
    [self.view addSubview:label];
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = ICRGB(0xbebebe);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"该文件暂不支持本地浏览，请使用其他应用打开";
    [label sizeToFit];
    label.centerX = App_Frame_Width * 0.5;
    UIButton *openBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    openBtn.frame     = CGRectMake(13, label.bottom + 40, App_Frame_Width-26, 48);
    [self.view addSubview:openBtn];
    openBtn.layer.cornerRadius = 5;
    openBtn.layer.masksToBounds = YES;
    openBtn.backgroundColor = ICRGB(0x12a2d7);
    //[openBtn setBackgroundImage:[UIImage imageNamed:@"icon_chat_file_bg"] forState:UIControlStateNormal];
    [openBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [openBtn setTitle:@"使用其他应用打开" forState:UIControlStateNormal];
    [openBtn addTarget:self action:@selector(otherApplicationOpen) forControlEvents:UIControlEventTouchUpInside];
}

- (void)webViewLoadData:(NSString *)type
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSURL *baseUrl = [NSURL fileURLWithPath:[paths objectAtIndex:0]];
    
    
    NSData *data = [[NSData alloc] initWithContentsOfFile:self.filePath];
    NSString *MIMEType = [NSString stringWithFormat:@"text/%@",type];
    [self.webView loadData:data MIMEType:MIMEType textEncodingName:@"UTF-8" baseURL:baseUrl];
}

- (void)otherApplicationOpen
{
    UIDocumentInteractionController *documentController =[UIDocumentInteractionController interactionControllerWithURL:self.fileURL];
    self.documentInCtr = documentController;  // 必须强引用起来
    [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    documentController.delegate = self;
}

#pragma mark -

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}


#pragma mark - QLDelegate
- (id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    return self.fileURL;
}

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1;
}

#pragma mark - webViewDelegate

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages() { "
     "var myimg,oldwidth;"
     "var maxwidth=350;"
     "for(i=0;i <document.images.length;i++){"
     "myimg = document.images[i];"
     "if(myimg.width > maxwidth){"
     "oldwidth = myimg.width;"
     "myimg.width = maxwidth;"
     "myimg.height = maxwidth * (myimg.height/oldwidth);"
     "}"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_audioView releaseTimer];
}

- (void)dealloc
{
    [_audioView releaseTimer];
}

@end
